<script setup lang="ts">
import type { MenuProps } from './menu'
import { Icon } from '@iconify/vue'
import { useRouter } from 'vue-router'

defineProps<{
  level: number
}>()

const menus = defineModel<MenuProps[]>({ required: true })

function extendMenu(menu: MenuProps, isOpen: boolean) {
  for (let i = 0; i < menus.value.length; i++) {
    const m = menus.value[i]
    if (m.children && m.children.length > 0) {
      if (m === menu) {
        m.isOpen = isOpen
      }
    }
  }
  // 关闭子级菜单
  if (!isOpen) {
    closeMenu(menu)
  }
}
function closeMenu(menu: MenuProps) {
  if (menu.children && menu.children.length > 0) {
    menu.isOpen = false
    for (let i = 0; i < menu.children.length; i++) {
      closeMenu(menu.children[i])
    }
  }
}

const router = useRouter()

/**
 * 点击菜单
 */
function clickItem(menu: MenuProps) {
  if (hasChildren(menu)) {
    extendMenu(menu, !menu.isOpen)
  }
  else if (menu.path) {
    router.push(menu.path)
  }
}

function hasChildren(menu: MenuProps) {
  return menu.children && menu.children.filter(child => child.isHide === undefined ? true : !child.isHide).length > 0
}
</script>

<template>
  <ul class="menu" :style="`--menu-level:${level}`">
    <template
      v-for="(m, index) in menus" :key="index"
    >
      <li
        v-if="m.isHide === undefined ? true : !m.isHide"
        class="menu-item"
        :class="[
          m.isActive ? 'active' : '',
        ]"
      >
        <div
          class="menu-item-content flex flex-row items-center justify-between"
          @click="clickItem(m)"
        >
          <div v-if="m.icon" class="menu-icon">
            <Icon :icon="m.icon" />
          </div>
          <div class="flex-1 truncate">
            {{ m.title }}
          </div>
          <div
            v-if="hasChildren(m)"
            :class="`i-tdesign-chevron-down ${m.isOpen ? 'rotate-180' : ''} w-6 transition-transform`"
          />
        </div>
        <MenuTransition>
          <Menu
            v-if="hasChildren(m) && m.children"
            v-show="m.isOpen"
            v-model="m.children"
            :level="level + 1"
            :class="[
              m.isActive ? 'active' : '',
            ]"
          />
        </MenuTransition>
      </li>
    </template>
  </ul>
</template>

<style scoped>
.menu {
  --at-apply: list-none p-0 m-0 text-sm;
}
.menu-item-content {
  --at-apply: h-10 mx-2 my-0.5 cursor-pointer hover-bg-secondary hover-text-active;
  padding-left: calc(10px + var(--menu-level) * 20px);
  width: calc(200px - 10px - var(--menu-level) * 20px);
}

.menu-icon {
  --at-apply: w-6;
}
.menu-item-content:hover .menu-icon {
  --at-apply: scale-110 transition-transform;
}

.menu-item.active > .menu-item-content {
  --at-apply: text-active;
}

.menu-item.active:not(:has(.menu)) > .menu-item-content {
  --at-apply: bg-active;
}
</style>
